var OVERRIDES = {
	"LIF16EM56A12FSB": { "sortname": "Middle Valley Clearing Forest Community Machine Room" }
	, "LCRC6VC9MAO1Q7F": { "sortname": "Groddle Forest Junction Subway Station" }
	, "LHV38BSD7G32CMQ": { "sortname": "Navran Dissent Model Home" }
	, "LCR101Q98A12EHH": { "sortname": "Otterlane Meadow Community Machine Room" }
	, "LHV3O6D3AG32NTH": { "sortname": "Stora Rede Model Home" }
	, "LCR1HMTBS2O1EGT": { "sortname": "Tii Street, 1100 block" }
	, "LCR132T309L1CGI": { "sortname": "Tii Street, 1200 block" }
	, "LCR1313309L135T": { "sortname": "Tii Street, 2100 block" }
	, "LCR13VMB09L1MIJ": { "sortname": "Tii Street, 2200 block" }
	, "LCR1HLGAS2O1BLB": { "sortname": "Tii Street, 3100 block" }
	, "LCR13GS509L1K6U": { "sortname": "Tii Street, 3200 block" }
	, "LCR13UEA09L1J19": { "sortname": "Tii Street, 3300 block" }
	, "LCR140BC09L1PPJ": { "sortname": "Tii Street, 4200 block" }
	, "LCR141HD09L1273": { "sortname": "Tii Street, 4300 block" }
	, "LIFS7GEIVV72UTS": { "sortname": "Tii Street, 1300 block" }
	, "LIFU2S7400827JO": { "sortname": "Tii Street, 1400 block" }
	, "LIFD8TP75QA2IA0": { "sortname": "Tii Street, 2300 block" }
	, "LIFK24S95N6200T": { "sortname": "Tii Street, 2400 block" }
	, "LIFD07C55QA2T9G": { "sortname": "Tii Street, 3400 block" }
	, "LIFS4V1IVV723OT": { "sortname": "Tii Street, 4100 block" }
	, "LIFK3HAA5N62FCM": { "sortname": "Tii Street, 4400 block" }
	, "LIFD5MR65QA2HGR": { "sortname": "Tii Street, 5100 block" }
	, "LIFSAL8JVV727I3": { "sortname": "Tii Street, 5200 block" }
	, "LIFTE11SVV72AFH": { "sortname": "Tii Street, 5300 block" }
	, "LIFK4LLA5N62LIL": { "sortname": "Tii Street, 5400 block" }
	, "LHVEUUABN852LEO": { "sortname": "Rappam Rolls, 1100 block" }
	, "LHVF0OSBN8521I6": { "sortname": "Rappam Rolls, 2100 block" }
	, "LCR1K1MK5ST1ARN": { "sortname": "Froughtful Fen, Froughtful Arms Apartments" }
	, "LA9MU59GB792T80": { "sortname": "Canary Send, Besara Community Machine Room" }
	, "LA9EV3R9BTA2EIF": { "sortname": "Fitadara Fry Loft, 101" }
	, "LA9ESFQ9BTA2NPK": { "sortname": "Fitadara Fry Loft, 102" }
	, "LA9EU1R9BTA252O": { "sortname": "Fitadara Fry Loft, 201" }
	, "LA9EVER9BTA2HNC": { "sortname": "Fitadara Fry Loft, 202" }
	, "LA9ETMR9BTA21T9": { "sortname": "Fitadara Fry Loft, 203" }
	, "LA9EUDR9BTA28JC": { "sortname": "Fitadara Fry Loft, 301" }
	, "LA9F0LR9BTA2QTS": { "sortname": "Fitadara Fry Loft, 401" }
	, "LA9F0DR9BTA2P30": { "sortname": "Fitadara Fry Loft, 402" }
	, "LA9ERKQ9BTA2G55": { "sortname": "Fitadara Fry Loft, 403" }
	, "LA9ES7Q9BTA2LP3": { "sortname": "Fitadara Fry Loft, 404" }
	, "LA9ET7Q9BTA2TCL": { "sortname": "Fitadara Fry Loft, 405" }
	, "LA9F05R9BTA2N5G": { "sortname": "Fitadara Fry Loft, 406" }
};

var THROTTLE_INTERVAL = 0.9;	// in seconds

var p_script_start, p_script_end;

$(document).ready(function() {

	/*
		Wrapper class around the Glitch API.. I love GAPIs!
	*/
	function GAPI() {};
	GAPI.locations = {};
	GAPI.locations.getStreets = function(hub_id) {
		api_call('locations.getStreets', { 'hub_id': hub_id + '' }, function(r) {
			if (r.ok) {
				processHubStreets(r.name, r.streets);
			} else { console.error('OOPS something went wrong with locations.getStreets: ' + e.error); }
		});
	}
	GAPI.locations.streetInfo = function(street_tsid) {
		api_call('locations.streetInfo', { 'street_tsid': street_tsid + ''}, function(r) {
			if (r.ok) {
				print(" .", true);
				processConnections(r.connections);
			} else { console.error('OOPS something went wrong with locations.streetInfo: ' + e.error); }
		});
	}
	/* ------------------------------------------------ */

	p_script_start = new Date().getTime();
	
	function print(msg, append) {
		if (!append) {
			$('#locJson').text(msg);
		} else {
			$('#locJson').text($('#locJson').text() + msg);
		}
	}
	
	function log404(street_tsid) {
		$('#loc404').append('<li style="float: left; border-right: solid 1px #aaa; padding-right: 5px; padding-left: 5px; margin-bottom: 2px; "><a target="_blank" href="http://' + window.location.host + '/locations/' + street_tsid + '">' + _streets[street_tsid].name 
			+ ' (' + _streets[street_tsid].region + ')</a></li>');
	}

	var LOC_DIALOG = '<div class="dialog" id="locDialogueCont">'
		+ '<div class="dialog-inner" id="slocDialogue" style="overflow: auto !important; height: 450px !important;">'
		+ '<a class="close" href="javascript: void(0);" id="locDialogueclose">Close</a>'
		+ '<h2>Generate Locations</h2>'
		+ '<div style="float: left;"><a id="locRunBtn" href="javascript: void(0);" class="button-tiny button-minor">Run!</a></div>'
		+ '<br style="clear:both;" />'
		+ '<textarea style="margin-top: 10px; width: auto !important;" cols="80" rows="10" readonly id="locJson"></textarea>'
		+ '<div style="width:100%; margin-top: 3px; font-size: 0.9em; color: #999;" id="timetaken">Time taken: </div>'
		+ '<h3 style="margin-top: 10px; font-size: 1.8em; ">404 Pages</h3>'
		+ '<ul id="loc404"></ul>'
		+ '</div>'
		+ '</div>';
			
	$(document).ready(function() {
		// Wire up UI
		$("body").append(LOC_DIALOG);
		$("#locDialogueclose").click(hideLocDialogue);
		$('.label-menu ul').after('<a class="button-tiny button-minor" href="javascript: void(0);" id="linkLocDialogue">Location Helper</a>');
		$("#linkLocDialogue").click(showLocDialogue);
		$("#locRunBtn").click(function() {
			print('Running ...', true);
			api_call('locations.getHubs', {}, function(r) { 
				if (r.ok) { processHubs(r.hubs); }
			});
		});
		hideLocDialogue();
	});	// $(document).ready

	function showLocDialogue() {
		$("#locDialogueCont").show();
	}
	function hideLocDialogue() {
		$("#locDialogueCont").hide();
	}

	var _hubs = {};
	var _hubCount = 0;
	var _streets = {};
	var _streetCount = 0;
	function generateSlug(name) {
		return name.replace(/\s+/g, "").toLowerCase();
	}

	function processHubs(hubs) {
		_hubs = hubs;
		print('Getting hub streets ...', false);
		var loop = 0;
		for (hub_id in _hubs) {
			_hubCount++;
			loop++;
			setTimeout(GAPI.locations.getStreets, loop*0.5*THROTTLE_INTERVAL*1000, [hub_id]);
		}
	}
	
	function processHubStreets(hubName, streets) {
		_hubCount--;
		hubSlug = generateSlug(hubName);
		for (street_tsid in streets) {
			if (_streets[street_tsid]) { continue; }
			_streets[street_tsid] = { "name": streets[street_tsid].name, "region": hubSlug };
		}
		if (_hubCount != 0) { return; }	// not all hub streets processed
		
		print("Extracted hubs ...", false);
		// continue to process connections
		var loop = 0;
		for (street_tsid in _streets) {
			_streetCount++;
			loop++
			setTimeout(GAPI.locations.streetInfo, loop*0.5*THROTTLE_INTERVAL*1000, [street_tsid]);
		}
	}
	
	function processConnections(connections) {
		_streetCount--;
		var hubSlug;
		for (street_tsid in connections) {
			if (_streets[street_tsid]) { continue; }
			hubSlug = generateSlug(connections[street_tsid].hub.name);
			_streets[street_tsid] = { "name": connections[street_tsid].name, "region": hubSlug };			
		}
		if (_streetCount != 0) { return; }	// not all connections processed
		
		print("Processing Connections ...", false);
		var cloneStreets = _streets;
		var loop = 0;
		for (street_tsid in cloneStreets) { 
			_streetCount++;
			loop++;
			setTimeout(scrapePage, loop*THROTTLE_INTERVAL*1000, [street_tsid]);
		}
	}
	function scrapePage(street_tsid) {
		street_tsid = street_tsid + '';
		print(" .", true);
		$.get("http://" + window.location.host + "/locations/" + street_tsid,
			function(data) {
				print(" .", true);
				_streetCount--;
				var page = $(data);
				var is404 = (page.find('h1').text() == 'Page not found');
				if (is404) { 
					console.log('Something is not found: ' + _streets[street_tsid].name + ' http://' + window.location.host + '/locations/' + street_tsid); 
					log404(street_tsid);
					delete _streets[street_tsid];	// remove it
				}
				
				if (!is404) {
					var this_street_tsid = page.find('form').attr('action').match(/\/locations\/([A-Z,0-9]+)\//)[1];
					var this_street_name = page.find('h1').text();
					
					var landmarks = page.find('div.guide-landmarks ul li a, div.guide-connect ul li a');
					var region = generateSlug(page.find('h2.subtitle').text().match(/^in (.*)$/)[1]);
					
					for (var i = 0; i < landmarks.length; i++) {
						var name = landmarks[i].innerHTML;
						var landmark_street_tsid = landmarks[i].attributes["href"].value.match(/\locations\/([0-9,A-Z]+)/)[1];
						
						if (_streets[landmark_street_tsid]) { continue; }	// been there, done that
						_streets[landmark_street_tsid] = { "name": name, "region": region };
						
						print("Scraping " + landmark_street_tsid + " " + name, false);
						_streetCount++;
						var loop = i + 1 + _streetCount;
						console.log('loop: ' + loop);
						setTimeout(scrapePage, loop*THROTTLE_INTERVAL*1000, [landmark_street_tsid]);
					}
				}

				if (_streetCount == 0) {
					// do pruning
					print("Pruning ...", false);
					$.get("http://" + window.location.host + "/locations/?norun=1",
						function(data) {
							var listed = [];
							//var locPage = $(data);
							$(data).find('ul.list a').each(function() {
								delete _streets[$(this).attr("href").split("/")[2]];	// remove location already listed
							});
							
							print("Sorting ...", false);
							var sortedStreets = [];
							for (street_tsid in _streets) {
								s = _streets[street_tsid];
								s = { 'street_tsid': street_tsid, 'name': s.name, 'region': s.region };
								if (OVERRIDES[street_tsid]) { s.sortname = OVERRIDES[street_tsid].sortname; }
								sortedStreets.push(s);
							}
							sortedStreets = $(sortedStreets).sort(sortStreets);
							
							// format it
							_streets = {};
							for (var i = 0; i < sortedStreets.length; i++) {
								s = sortedStreets[i];
								_streets[s.street_tsid] = { 'name': s.name, 'region': s.region };
								if (s.sortname) {
									_streets[s.street_tsid].sortname = s.sortname;
								}
							}
							// dump out final output
							print('var locations = (' + JSON.stringify(_streets, null, 4) + ');', false); 
							p_script_end = new Date().getTime();
							$('#timetaken').html('Time taken: ' + format_sec((p_script_end-p_script_start)/1000));
						}
					);
					
					
				}
		});	// $.get : function(data) {
	}	// function scrapePage(street_tsid) {
	
	function sortStreets(a, b) {
		var nameA = (a.sortname ? a.sortname : a.name);
		var nameB = (b.sortname ? b.sortname : b.name);
		if (nameA > nameB) { return 1; }
		return -1;
	}
});
